package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import cn.jpush.android.api.JPushInterface;
import com.lzx.iteam.net.*;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.TimeButton;
import com.lzx.iteam.widget.kpswitch.util.KeyboardUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shijunting on 14-12-29.
 */
public class RegisterActivity extends Activity implements View.OnClickListener {

    private Button mBtnReg;
    private TimeButton mRegTimeBtn;
    private EditText mPhoneNumberEt, mVerifycodeEt, mSetPasswdEt;
    private CheckBox mCheckArgreement;
    private Dialog mProgressDialog;
    private TextView mBack,mAgreement,mTitle;
    private TextView mTvLogin,mTvForget;

    private String mPasswd;
    private String mPhoneNum;
    private PreferenceUtil mPreferenceUtil;
    private LocalLogin loginer;
    public static RegisterActivity instance = null;

    public static final int ERROR_PARSE = 1003;
    private static final int MSG_ACTIVE = 2001;
    private static final int MSG_SEND_VERIFY_CODE = 2000;
    public static final String LAST_NUMBER = "last_number";
    private static final String TAG = "RegisterActivity";
    private AsynHttpClient mAsynClient;

    private static final int MSG_GET_EVENT_LIST = 2007;
    private static final int MSG_GET_CLOUD_GROUP_LIST = 2009;

    private static final int MSG_SET_REGISTRATION_ID = 1000;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what){
                case MSG_SEND_VERIFY_CODE:
                    if (msg.arg1 == 0) {
                        showAlertDialog();
                    }else {
                        mRegTimeBtn.onClearTask();
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(RegisterActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(RegisterActivity.this,(String)msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case MSG_ACTIVE:
                    mPreferenceUtil.save(PreferenceUtil.TEAM_SID,LocalLogin.getInstance().mSid);
                    mPreferenceUtil.save(PreferenceUtil.USER_PHONE,mPhoneNum);
                    mPreferenceUtil.save(PreferenceUtil.USER_PASS,mPasswd);
                    handleActiveDone(msg);
                    break;
                case MSG_GET_EVENT_LIST:
                    httpReqDlgDismiss();
                    mPreferenceUtil.save("isLogin","yes");
                    mPreferenceUtil.save("Other_login",0);  // 其他设备登录标识
                    Intent intent = new Intent();
                    intent.setClass(RegisterActivity.this,MySettingActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    RegisterActivity.this.finish();
                    break;
                case MSG_GET_CLOUD_GROUP_LIST:
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_user_layout);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        loginer = LocalLogin.getInstance();
        init();
        saveKeyBoardHeight();
        instance = this;

        mRegTimeBtn.onCreate(savedInstanceState);
        mRegTimeBtn.setOnClickListener(this);
        mRegTimeBtn.setTextBefore("获取验证码").setTextAfter("秒后重新获取").setLenght(60*1000);

    }

    /**
     * 初始化
     */
    private void init() {

        mCheckArgreement = (CheckBox) findViewById(R.id.privacy_agreement_check);
        mBtnReg = (Button) findViewById(R.id.btn_reg);
        mRegTimeBtn = (TimeButton) findViewById(R.id.reg_btn_time);
        mPhoneNumberEt = (EditText) findViewById(R.id.phonenumber);
        mVerifycodeEt = (EditText) findViewById(R.id.verifycode);
        mSetPasswdEt = (EditText) findViewById(R.id.set_passwd);
        mTitle = (TextView) findViewById(R.id.regist_tv_title);
        mAgreement = (TextView) findViewById(R.id.privacy_agreement_tv);
        mAgreement.setOnClickListener(this);
        mAsynClient = AsynHttpClient.getInstance(this);
        mPhoneNumberEt.setFocusable(true);
        mPhoneNumberEt.setFocusableInTouchMode(true);
        mPhoneNumberEt.requestFocus();
        mBtnReg.setOnClickListener(this);
        mTvLogin = (TextView) findViewById(R.id.tv_no_account);
        mTvForget = (TextView) findViewById(R.id.tv_forget_password);
        mTvLogin.setOnClickListener(this);
        mTvForget.setOnClickListener(this);

    }

    private void initViewDisplay() {
            String number = mPreferenceUtil.getString(LAST_NUMBER,"");
            if (!TextUtils.isEmpty(number))
                mPhoneNumberEt.setText(number);
    }

    /**
     * 获取软键盘的高度并保存
     */
    private void saveKeyBoardHeight(){
        final View decorView = getWindow().getDecorView();
        decorView.getViewTreeObserver().
                addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    /**
                     * the result is pixels
                     */
                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                        decorView.getWindowVisibleDisplayFrame(r);
                        int screenHeight = decorView.getRootView().getHeight();
                        int heightDifference = screenHeight - (r.bottom - r.top);
                        Log.e("KeyboardSize", "KeyboardSize:  " + heightDifference);
                        if (heightDifference > 200){
                            KeyboardUtil.saveKeyboardHeight(RegisterActivity.this, heightDifference - r.top);
                        }
                    }
                });
    }


    @Override
    protected void onResume() {
        super.onResume();
        initViewDisplay();
    }

    /**
     * 获取验证码
     */
    private void sendVerifyCode() {

        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_NEW_PHONE,LocalLogin.getInstance().mPhoneNum));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE,"1"));

        SendVerifyCodeMessage mobileActiveMsg = new SendVerifyCodeMessage(
                mHandler.obtainMessage(MSG_SEND_VERIFY_CODE));
        mobileActiveMsg.type = 2;
        mobileActiveMsg.mParams = mList;
        mobileActiveMsg.mApi = AsynHttpClient.API_USER_SEND_CODE;
        mAsynClient.execUserHttp(mobileActiveMsg);
    }


    /**
     *  注册返回的处理
     * @param msg
     */
    private void handleActiveDone(Message msg) {
        if (msg.arg1 == 0) {
//            getEventsList("0", 1);
//            getCloudGroupList();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(RegisterActivity.this.getCurrentFocus()
                    .getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            httpReqDlgDismiss();
            mPreferenceUtil.save("isLogin","yes");
            mPreferenceUtil.save("Other_login",0);  // 其他设备登录标识
            Intent intent = new Intent();
            intent.setClass(RegisterActivity.this,MySettingActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            RegisterActivity.this.finish();

        } else {
            httpReqDlgDismiss();
            mRegTimeBtn.onClearTask();
            if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                Toast.makeText(RegisterActivity.this, R.string.active_failure_no_network,
                        Toast.LENGTH_LONG).show();
            } else{
                Toast.makeText(RegisterActivity.this, (String) msg.obj,
                        Toast.LENGTH_LONG).show();

            }

            AllDialogUtil util = new AllDialogUtil(RegisterActivity.this);
            util.titleMsgBtnStyle("错误", "注册失败!", "确定");
            mRegTimeBtn.onClearTask();
            util.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
                @Override
                public void onConfirmClick(Dialog lDialog) {
                    lDialog.dismiss();
                }

                @Override
                public void onCancelClick(Dialog lDialog) {
                }
            });
        }
    }


    /**
     * 验证码 message  RegMsgStructure
     */
    static class SendVerifyCodeMessage extends CcMsgStructure {

        private Message mmCallback;

        public SendVerifyCodeMessage(Message callback) {
            mmCallback = callback;
        }

        @Override
        public void onReceive(JSONObject data) {
            try {
                if (mmCallback != null) {
                    mmCallback.arg1 = 0;
                    mmCallback.sendToTarget();
                }
            } catch (Exception e) {
                if (mmCallback != null) {
                    mmCallback.arg1 = AsynHttpClient.ERROR_SERVER;
                    mmCallback.sendToTarget();
                }
                return;
            }

        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if(mmCallback != null){
                mmCallback.arg1 = error;
                if(!StringUtil.isEmpty(errorMsg)){
                    mmCallback.obj = errorMsg;
                }else{
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    /**
     * 点击按钮 进行的判断
     * @param checkcode true-注册按钮 false-获取验证码按钮
     * @return
     */
    private boolean localCheck(boolean checkcode) {
        mPhoneNum = mPhoneNumberEt.getText().toString().trim();
        mPasswd = mSetPasswdEt.getText().toString().trim();
        String code = mVerifycodeEt.getText().toString().trim();

        LocalLogin.getInstance().mPhoneNum = mPhoneNum;

        if (TextUtils.isEmpty(mPhoneNum)) {
            Toast.makeText(this, R.string.validate_phone_num, Toast.LENGTH_LONG).show();
            return false;
        }

        if (checkcode) {
            if (TextUtils.isEmpty(code)) {
                Toast.makeText(this, R.string.active_code_empty, Toast.LENGTH_LONG).show();
                return false;
            } else if (code.length() < 4) {
                Toast.makeText(this, R.string.active_code_error, Toast.LENGTH_LONG).show();
                return false;
            }
            if (TextUtils.isEmpty(mPasswd) || mPasswd.length() < 6) {
                Toast.makeText(this, R.string.validate_passwd, Toast.LENGTH_LONG).show();
                return false;
            }

        }

        if (!StringUtil.isMobile(mPhoneNum)) {
            Toast.makeText(this, R.string.validate_china_phone_num, Toast.LENGTH_LONG).show();
            return false;
        }

        if (!mCheckArgreement.isChecked()) {
            Toast.makeText(this, R.string.validate_privacy_agreement, Toast.LENGTH_LONG).show();
            return false;
        }

        return true;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.reg_btn_time:
                if (localCheck(false)){
                    if (Constants.isConnect(RegisterActivity.this)){
                        sendVerifyCode();
                        mRegTimeBtn.startTime();
                        mPreferenceUtil.save(LAST_NUMBER, mPhoneNum);
                    }else{
                        Toast.makeText(RegisterActivity.this,R.string.active_failure_no_network,Toast.LENGTH_SHORT).show();
                    }
                }
                break;

            case R.id.btn_reg:
                if (localCheck(true)) {
                    showConfirmDialog();
                }
                break;
            case R.id.container_back:
                finish();
                break;
            case R.id.privacy_agreement_tv:
                if (Constants.isFastClick()) {
                    return;
                }
//                Intent intent = new Intent(this,AgreementActivity.class);
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "使用条款和隐私政策");
                intent.putExtra("type", -2);
                startActivity(intent);
                break;
            case R.id.tv_no_account:
                Intent login = new Intent(RegisterActivity.this, LoginActivity.class);
                login.putExtra("regist",true);
                startActivity(login);
                break;
            case R.id.tv_forget_password:
                Intent forget = new Intent(RegisterActivity.this, ForgetActivity.class);
                startActivity(forget);
                break;
        }
    }

    /**
     * 确认对话框
     */
    private void showConfirmDialog() {
        String title = getString(R.string.active_tongxingzheng_tv1);
        String message = getString(R.string.active_tongxingzheng_tv2);
        AllDialogUtil dialogUtil = AllDialogUtil.getInstance(RegisterActivity.this);
        dialogUtil.titleMsgBtnStyle(title, message, getString(R.string.active),
                getString(R.string.active_read_agreement));
        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                String code = mVerifycodeEt.getText().toString();
                if (!TextUtils.isEmpty(code)) {
                    mobileActive(code);
                } else {
                    Toast.makeText(RegisterActivity.this, R.string.active_code_empty,
                            Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
                showPrivacyAgreement();
            }
        });
    }

    /**
     * 跳转至使用条款与隐私政策页面
     */
    private void showPrivacyAgreement() {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra("title", "使用条款和隐私政策");
        intent.putExtra("type", -2);
        startActivity(intent);
    }

    /**
     *   注册请求
     * @param verifyCode 验证码
     */
    public void mobileActive(String verifyCode) {

        TelephonyManager tManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // add a "a_" prefix in order to distinguish from iPhone
        // TODO 当验证码超过三次时，用dId替换tManager.getDeviceId()，随便改did里面一个数字,超过再改
//        String dId = "10C1221B-BA3E-0CEE-1830-5E35A5F2D034";
//        String devId = "a_" + dId;
        String devId = "a_" + tManager.getDeviceId();
        String osVersion = Constants.getVersionName(this);


        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_NEW_PHONE,LocalLogin.getInstance().mPhoneNum));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_PASS,mPasswd));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE,"1"));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_NAME,"Android "+android.os.Build.VERSION.RELEASE));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_NO,devId));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_APP_VERSION,osVersion));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_CODE,verifyCode));


        httpReqDlgShow();

        MobileActiveMessage mobileActiveMsg = new MobileActiveMessage(this,
                mHandler.obtainMessage(MSG_ACTIVE));
        mobileActiveMsg.type = 2;
        mobileActiveMsg.mParams = mList;
        mobileActiveMsg.mApi = AsynHttpClient.API_USER_REGIST;
        mAsynClient.execUserHttp(mobileActiveMsg);

    }





    private void httpReqDlgShow() {
        if (mProgressDialog == null) {
            mProgressDialog = AllDialogUtil.getInstance(this).styleProgress("请稍后...");
            mProgressDialog.setCancelable(false);
        }
        mProgressDialog.show();
    }

    private void httpReqDlgDismiss() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }


    /**
     *  注册请求的  message
     */
     class MobileActiveMessage extends CcMsgStructure {

        private Context mmContext;

        private Message mmCallback;


        public MobileActiveMessage(Context context, Message callback) {
            mmCallback = callback;
            mmContext = context;
        }

        @Override
        public void onReceive(JSONObject data) {

                try{

                    JSONObject result = data.getJSONObject("data");
                    LocalLogin.getInstance().mSid  = result.getString(AsynHttpClient.KEY_SID_OLD);
                    String useId = result.getString(AsynHttpClient.KEY_NEW_USEID);
                    Log.i("my_useid","uid ===   "+useId+"    sid == "+LocalLogin.getInstance().mSid);
                    mPreferenceUtil.save(PreferenceUtil.CLIENT_USEID, useId);

                    String securityKey = result.getString(PreferenceUtil.CLIENT_SECURITY_KRY);
                    mPreferenceUtil.save(PreferenceUtil.CLIENT_SECURITY_KRY, securityKey);

                    setRegistrationId(JPushInterface.getRegistrationID(mmContext));

                    if (!StringUtil.isEmpty(LocalLogin.getInstance().mSid)) {
                        StorageData storageData = new StorageData(LocalLogin.getInstance().mPhoneNum, LocalLogin.getInstance().mSid);
                        storageData.writeIn(mmContext, "key.obj");
                        loginer.login(RegisterActivity.this);
                        mmCallback.arg1 = 0;
                        mmCallback.obj = data;
                    } else {
                        mmCallback.arg1 = ERROR_PARSE;
                    }
                }catch (Exception e){

                }

            if (mmCallback != null)
                mmCallback.sendToTarget();
        }

        @Override
        public void onError(int error, Object ret) {

            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if(mmCallback != null){
                mmCallback.arg1 = error;
                if(!StringUtil.isEmpty(errorMsg)){
                    mmCallback.obj = errorMsg;
                }else{
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }

    private void showAlertDialog() {
        AllDialogUtil dialogUtil = AllDialogUtil.getInstance(this);
        String title = getString(R.string.alert_title);
        String message = getString(R.string.alert_message);
        dialogUtil.titleMsgBtnStyle(title, message, getString(R.string.ok));
        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
            }
        });
    }


    @Override
    protected void onDestroy() {
        mRegTimeBtn.onDestroy();
        super.onDestroy();
    }


    /**
     * 获取事件列表
     *
     * @param type 事件类型 0. 全部, 1：公告，2：审批，3：周报，4：普通事件，5：自定义  6:系统事件  7：活动 8：投票 9:签到
     */
    public void getEventsList(String type, int pageIndex) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TYPE, type));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, pageIndex * 10 + ""));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, "1"));
        EventDataMessage.GetEventListData eventListData = new EventDataMessage.GetEventListData(mHandler.obtainMessage(MSG_GET_EVENT_LIST), RegisterActivity.this, type,1);
        eventListData.mApi = AsynHttpClient.API_EVENT_LIST_V3;
        eventListData.mParams = nvps;
        AsynHttpClient.getInstance(RegisterActivity.this).execEventHttp(eventListData);
    }

    /**
     * 获取团队列表
     */
    public void getCloudGroupList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        GetGroupListMsg getGroup = new GetGroupListMsg(RegisterActivity.this,mHandler.obtainMessage(MSG_GET_CLOUD_GROUP_LIST));
        getGroup.mApi = AsynHttpClient.API_GROUP_GETLIST;
        getGroup.mParams = nvps;
        AsynHttpClient.getInstance(RegisterActivity.this).execCcHttp(getGroup);
    }

    /**
     * 绑定极光推送唯一 id
     * @param registrationId
     */
    private void setRegistrationId(String registrationId) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair("registration_id", registrationId));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(MSG_SET_REGISTRATION_ID));
        message.mApi = AsynHttpClient.API_APP_ANDROID_PUSH;
        message.mParams = mList;
        AsynHttpClient.getInstance(RegisterActivity.this).execUserHttp(message);

    }


}
